package com.gaogzhen.threadPool;

import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

@Slf4j(topic = "TestThreadPollExecutor03")
public class TestThreadPollExecutor03 {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        test02(pool);
        pool.shutdown();

    }

    public static void test02(ExecutorService pool) throws InterruptedException, ExecutionException {
        String result = pool.invokeAny(Arrays.asList(
                () -> {
                    log.debug("begin 1");
                    Thread.sleep(1000);
                    return "1";
                }, () -> {
                    log.debug("begin 2");
                    Thread.sleep(500);
                    return "2";
                }, () -> {
                    log.debug("begin 3");
                    Thread.sleep(2000);
                    return "3";
                }
        ));

        log.debug("result {}", result);
    }

    public static void test01(ExecutorService pool) throws InterruptedException {
        List<Future<String>> futures = pool.invokeAll(Arrays.asList(
                () -> {
                    log.debug("begin 1");
                    Thread.sleep(1000);
                    return "1";
                }, () -> {
                    log.debug("begin 2");
                    Thread.sleep(500);
                    return "2";
                },() -> {
                    log.debug("begin 3");
                    Thread.sleep(2000);
                    return "3";
                }
        ));

        futures.forEach(r -> {
            try {
                log.debug("get {}", r.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });
    }
}
